import qs from "qs";

// 创建axios实例
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: true,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
});

//取消axios请求
var CancelToken = axios.CancelToken;
Vue.prototype._cancels_ = [];

// 请求拦截器
instance.interceptors.request.use((_) => {
  const config = _;
  const IS_GET = config.method === "get";
  const data = (IS_GET ? config.params : config.data) || {};

  config.headers["Authorization"] = localStorage.getItem("token");

  // 解决数据加载过慢的问题
  config.cancelToken = new CancelToken((c) => {
    Vue.prototype._cancels_.push(c);
  });

  if (IS_GET) {
    data["_t"] = Date.now();
    config.params = data;
  } else {
    if (config.headers["Content-Type"] == "application/json") {
      config.data = data;
    } else {
      config.data = qs.stringify(data);
    }
  }

  return {
    ...config,
  };
});

// 响应拦截器
instance.interceptors.response.use(
  (response) =>
    Promise.resolve(response.data.data ? response.data.data : response.data),
  (error) => {
    console.log(error);
    if (error.response && error.response.data) {
      if (error.response.config.url !== "/auth/info") {
        // element由于是CDN，所以得这样写
        ELEMENT.Message({
          type: "error",
          message: error.response.data.message,
        });
      }
    }
    return Promise.reject(error.response);
  }
);

export default instance;
